package back

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"time"
	"tmall_go/models"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

type MineController struct{}
type PwdObj struct {
	OldPwd  string
	NewPwd  string
	ConfPwd string
}

var pwdObj = PwdObj{}

func (con MineController) Mine(c *gin.Context) {
	_, err := c.Cookie("id")
	if err != nil {
		// 用户登录过期
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	optTag := c.Param("optTag")
	// id, _ := strconv.Atoi(idStr)
	userObj := models.User{}
	// 从mysql数据库中获取
	// models.DB.Where("id=?", id).Find(&userObj)
	// 从redis数据库中获取
	jsonData, recErr := models.GetDataToRedis("golang_rdb:userInfo")
	if recErr != nil {
		fmt.Println("从redis中获取数据失败")
	}
	recErr = json.Unmarshal([]byte(jsonData), &userObj)
	if recErr != nil {
		fmt.Println("json转为结构体数据失败")
	}
	userName, _ := c.Cookie("name")
	c.HTML(http.StatusOK, "backstage/index.html", gin.H{
		"barKey":   4,
		"userName": userName,
		"errTag":   optTag, // 1 操作成功，-1失败，0 不显示
		"info":     userObj,
	})
}
func (con MineController) ChangePassword(c *gin.Context) {
	// 验证用户是否过期
	_, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	errStatus := c.Query("error")
	if errStatus == "" {
		pwdObj = PwdObj{}
	}
	c.HTML(http.StatusOK, "backstage/changePassword.html", gin.H{
		"optKey":    1,
		"errStatus": errStatus,
		"info":      pwdObj,
	})
}
func (con MineController) DoUptPassword(c *gin.Context) {
	// 验证用户是否过期
	idStr, err := c.Cookie("id")
	if err != nil {
		c.Redirect(http.StatusFound, "/back/login?error=3")
		return
	}
	id, _ := strconv.Atoi(idStr)
	oldPwd := c.PostForm("oldPwd")
	newPwd := c.PostForm("newPwd")
	confPwd := c.PostForm("confPwd")
	if newPwd != confPwd {
		// 确认密码错误
		pwdObj = PwdObj{
			OldPwd:  oldPwd,
			NewPwd:  newPwd,
			ConfPwd: confPwd,
		}
		c.Redirect(http.StatusFound, "/back/mine/changePassword?error=1")
		return
	}
	userObj := models.User{Id: id}
	models.DB.Find(&userObj)
	// 密码hash对比，不需要解密
	compErr := bcrypt.CompareHashAndPassword([]byte(userObj.Password), []byte(oldPwd))
	if compErr != nil {
		// 原密码错误
		pwdObj = PwdObj{
			OldPwd:  oldPwd,
			NewPwd:  newPwd,
			ConfPwd: confPwd,
		}
		c.Redirect(http.StatusFound, "/back/mine/changePassword?error=2")
		return
	}
	// bcrypt加密，后面通过它自带的方法进行密码对比
	resPwd, _ := bcrypt.GenerateFromPassword([]byte(newPwd), bcrypt.DefaultCost)
	userObj.Password = string(resPwd)
	userObj.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	models.DB.Save(&userObj)
	pwdObj = PwdObj{}
	c.Redirect(http.StatusFound, "/back/mine/opt/1")
}
